import {Config, Options, ResponseData} from "@/utils/apiInterface";
import {AxiosResponse} from "axios";
import request from "./apiManager";

/**
 * 展示加载动画
 * @param loading_flag 是否展示
 * @param loading_text 展示文本
 */
const apiShowLoading = (loading_flag:boolean, loading_text:string|undefined) =>{
	if (loading_flag) {
		// 加载提示
		uni.showLoading({
			title: loading_text,
			mask: true
		});
	}
};


// 返回值状态枚举
// eslint-disable-next-line no-shadow
enum CustomResponseCode {
	SUCCESS = 200, // 成功
	NO_TOKEN = 200001, // 没有token
	USER_BAN = 200002,
	NO_CODE = 2001003,
	// ...
}

/**
 * 发起网络请求
 * @param config 查看Config 接口
 * @param params 接口携带数据
 * @param options 查看Options 接口
 */
const networkRequest = (config:Config,params:Record<string, unknown> = {},options:Options = {})=> {
	const method = config.method === undefined ? "get" : config.method;
	const apiParams = config.apiParams === undefined ? {} : config.apiParams;
	const _loading = config.loading === undefined ? "加载中" : config.loading;
	const resultMode = config.resultMode === undefined ? false : config.resultMode;

	const loading = typeof options.loading !== "undefined" ? options.loading : _loading;

	return new Promise<ResponseData>((resolve, reject) => {
		if(_loading){
			apiShowLoading(true, loading);
		}
		params = { ...apiParams,
			...params
		};
		request({
			url: config.url,
			method,
			[method === "get" ? "params" : "data"]: params
		}).finally(() => {
			uni.hideLoading();
		})
			.then((response:AxiosResponse) => {
				const data = response.data;
				if(resultMode){
					resolve(data);
				}else{
					switch (response.data.code){
					case CustomResponseCode.SUCCESS:
						resolve(data);
						break;
					case CustomResponseCode.NO_TOKEN:
						// todo 统一处理无token
						break;
					case CustomResponseCode.USER_BAN:
						// todo 统一处理用户被封禁
						// 如果有需要 返回data
						reject(data);
						break;
					case CustomResponseCode.NO_CODE:
						wx.showToast({
							title: data.msg,
							icon: 'none'
						})
						reject(data);
						break;
					default:
						// 默认返回data 但推荐在枚举中列举异常状态
						reject(data);
					}
					// ...
				}
			}).catch(e => {
				console.log(e);
				// msg && _alert && _alert.toast(netWorkErrorMsg, 'cancel')
				// todo 当request status 404或者500等异常状态的处理
			});
	});
};

export {
	networkRequest
};
